﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using ECommerce.AuthService.Models;

namespace ECommerce.AuthService.Middlewares;

/// <summary>
/// 全局异常处理中间件
/// 捕获所有未处理的异常并返回统一格式响应
/// </summary>
public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    /// <summary>
    /// 执行中间件逻辑
    /// </summary>
    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(httpContext, ex);
        }
    }

    /// <summary>
    /// 处理异常并返回统一响应
    /// </summary>
    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        var response = context.Response;

        var result = new AuthResult
        {
            Success = false,
            Message = "发生未处理的异常"
        };

        switch (exception)
        {
            case ArgumentException ex:
                response.StatusCode = (int)HttpStatusCode.BadRequest;
                result.Message = ex.Message;
                break;
            default:
                response.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = "服务器内部错误，请稍后再试";
                break;
        }

        _logger.LogError(exception, "未处理的异常: {Message}", exception.Message);
        var json = JsonSerializer.Serialize(result);
        await context.Response.WriteAsync(json);
    }
}
